<template>
    <view>
        <block v-if="common_site_type == 1">
            <component-no-data propStatus="2" propMsg="展示型不允许提交订单"></component-no-data>
        </block>
        <block v-else>
            <view v-if="goods_list.length > 0" class="page-bottom-fixed">

                <view class="padding-horizontal-main padding-top-main bottom-line-exclude">
                    <!-- 商品数据 555-->
                    <view v-for="(group, index) in goods_list" :key="index" class="goods-group-list padding-main border-radius-main bg-white spacing-mb">
                        <!-- 仓库分组 -->
                        <view class="goods-group-hd oh br-b padding-bottom-main">
                            <view class="cp" @tap="warehouse_group_event" :data-value="group.url || ''">
                                <!-- <image v-if="(group.icon || null) != null" class="goods-group-icon va-m margin-right-xs" :src="group.icon" mode="aspectFit"></image> -->
								<text class="goods-group-title va-m">客户:</text>

								<uni-data-select v-if="showCustomer" style="padding: 2px;" placeholder="请选择客户" v-model="customerId"  :localdata="customerData" ></uni-data-select>
                                <input v-else v-model="customerName" disabled style="background-color: darkgray;border: 1px solid #e5e5e5;margin-top: 6px;padding: 2px;width: 100%;height: 35px;"  type="text" />


								<text class="goods-group-title va-m">送货日期:</text>
								<uni-datetime-picker type="date" return-type="timestamp" v-model="billDate"  /></uni-forms-item>
								<calendar v-model="showCalendar" @change="change" :isRange="false"></calendar>

								<text class="goods-group-title va-m">订单备注:</text>
								<input v-model="salRemark" style="border: 1px solid #e5e5e5;margin-top: 6px;padding: 2px;width: 100%;height: 35px;" type="text" />
                            </view>
                        </view>
                        <!-- 商品 -->
                        <view class="goods-content margin-bottom-sm">
                            <view v-for="(item, index2) in group.goods_items" :key="index2" class="goods-item padding-vertical-main oh br-b-dashed">
								<view v-if="item.images === null">
									<image :src="'https://zkerp.oss-cn-shenzhen.aliyuncs.com/public/'+item.title+'.png'"  mode="aspectFill" style="border: 1px solid bisque;margin:4px" class="goods-image fl radius"></image>
								</view>
								<view v-else>
									<image :src="item.images"  mode="aspectFill" style="border: 1px solid bisque;margin:4px" class="goods-image fl radius"></image>
								</view>

                                <view class="goods-base">
                                    <view class="goods-title multi-text">{{item.title}}</view>
                                    <view v-if="item.spec != null" class="margin-top-xs cr-gray">
										<text>{{item.spec}}</text>
                                    </view>
                                    <view class="oh pr margin-top-sm">
                                        <text class="fw-b">{{currency_symbol}}{{item.price}}</text>
										<text class="fw-b"><text class="cr-gray">x</text>{{item.stock}}</text>
                                        <text v-if="item.original_price > 0" class="original-price margin-left-sm">{{currency_symbol}}{{item.original_price}}</text>
                                        <text class="buy-number pa cr-gray">合计:{{currency_symbol}}{{item.price*item.stock}}</text>
                                    </view>
									<view>
										<input type="text" v-model="inputs[index2]" :ref="`child${item.id}`"  style="border: 1px solid #e5e5e5;margin-top: 6px;padding: 2px;width: 100%;float: left;height: 35px;" placeholder="请输入备注" />
									</view>
                                </view>
                            </view>
                        </view>
                        <!-- 小计 -->
                        <view class="oh tr goods-group-footer padding-top-xl">
                            <text v-if="group.order_base.total_price != group.order_base.total_price" class="original-price margin-right-sm">{{currency_symbol}}{{group.order_base.total_price}}</text>
                            <text class="sales-price">总计:{{currency_symbol}}{{group.order_base.actual_price}};共:{{group.order_base.buy_count}}件</text>
                        </view>
                    </view>

                </view>

                <!-- 导航 -->
                <view class="buy-nav oh wh-auto bg-white br-t bottom-line-exclude">
                    <view class="fr nav-submit padding-left-main">
                    </view>
					<view class="fr nav-submit padding-top padding-bottom padding-horizontal-main">
					    <button class="bg-main cr-white round text-size" type="default" @tap="buy_submit_event" :disabled="buy_submit_disabled_status" hover-class="none">提交订单</button>
					</view>

                </view>
            </view>

            <view v-if="goods_list.length == 0">
                <component-no-data :propStatus="data_list_loding_status" :propMsg="data_list_loding_msg"></component-no-data>
            </view>
        </block>
    </view>
</template>
<script>
    const app = getApp();
    import base64 from '../../common/js/lib/base64.js';
    import componentNoData from "../../components/no-data/no-data";
	import calendar from "../../components/calendar/l-calendar.vue"

    export default {
        data() {
            return {
				showCustomer:false,
				customerName:"",
				customerData:[],
				customerId:"",
				salRemark:"",
				billDate:"",
				showCalendar:false,
				inputs: [],
				user: null,
                data_list_loding_status: 1,
                buy_submit_disabled_status: false,
                data_list_loding_msg: '',
                params: null,
                payment_list: [],
                goods_list: [],
                total_price: 0,
                user_note_value: '',
                user_note_status: false,
                is_first: 1,
                extension_data: [],
                payment_id: 0,
                common_site_type: 0,
                extraction_address: [],
                site_model: 0,
                buy_header_nav: [
                    { name: "快递邮寄", value: 0 },
                    { name: "自提点取货", value: 2 }
                ],
                // 基础配置
                currency_symbol: app.globalData.data.currency_symbol,
                common_order_is_booking: 0,
				remark:"",//明细备注
            };
        },

        components: {
            componentNoData,calendar
        },
        props: {},

        onLoad(params) {
			console.log("----",params)
            // params.data 参数 urlencode(base64_encode(json字符串))
            //  buy_type 下单类型（goods 立即购买、cart 购物车）
            //  goods_data 下单商品urlencode(base64_encode(json字符串[{goods_id,stock,spec}]))
            //  params['data'] = '{"buy_type":"goods","goods_data":"W3siZ29vZHNfaWQiOiI5Iiwic3RvY2siOjEsInNwZWMiOlt7InR5cGUiOiLpopzoibIiLCJ2YWx1ZSI6IueyieiJsiJ9LHsidHlwZSI6IuWwuueggSIsInZhbHVlIjoiTCJ9XX1"}';
            //  ids 购物车主键ids
            if ((params.data || null) != null) {
                this.setData({
                    params: JSON.parse(base64.decode(decodeURIComponent(params.data))),
                    plugins_points_status: app.globalData.get_config('plugins_base.points.data.is_default_use_points', null) == 1
                });

                // 删除地址缓存
                uni.removeStorageSync(app.globalData.data.cache_buy_user_address_select_key);
            }
        },

        onShow() {
			this.user =app.globalData.get_user_cache_info(),
            // 数据加载
            this.init();
            this.setData({
                is_first: 0
            });
			this.getCurrentTime();
            // 初始化配置
            this.init_config();
			this.initCustomer();
        },

        // 下拉刷新
        onPullDownRefresh() {
            this.init();
        },

        methods: {
			getCurrentTime() {
			      const now = new Date();
			      const year = now.getFullYear();
			      const month = now.getMonth() + 1;
			      const day = now.getDate();
			      const hour = now.getHours();
			      const minute = now.getMinutes();
			      const second = now.getSeconds();

			      this.billDate = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
			},
			initCustomer(){

				console.log("--this.user--",this.user)
				if(this.user.userIdentity === 3){
					this.customerId =this.user.userIdentityList[0].id;
					this.customerName =this.user.userIdentityList[0].name;

					this.showCustomer =false;
				}else{
					this.showCustomer =true;
					uni.request({
					    url: app.globalData.get_request_url("getCustomer"),
					    method: 'GET',
					    data: {},
						header:{
							'Tenant-Id':this.user.role.tenantId,
							'X-Access-Token':this.user.token,
						},
					    dataType: 'json',
					    success: res => {
							console.log("---------",res);
							if(res.data.code == 200){
								this.customerData =res.data.result;
							}
						}
					})
				}

			},
			openCalendar(){
				this.showCalendar =true;
			},
            // 初始化配置
            init_config(status) {
                if ((status || false) == true) {
                    this.setData({
                        currency_symbol: app.globalData.get_config('currency_symbol'),
                        common_order_is_booking: app.globalData.get_config('config.common_order_is_booking'),
                        plugins_points_status: app.globalData.get_config('plugins_base.points.data.is_default_use_points', null) == 1
                    });
                } else {
                    app.globalData.is_config(this, 'init_config');
                }
            },

            // 获取数据
            init() {
                // 订单参数信息是否正确
                if (this.params == null) {
                    this.setData({
                        data_list_loding_status: 2,
                        data_list_loding_msg: '商品信息有误'
                    });
                    uni.stopPullDownRefresh();
                    return false;
                }

                // 本地缓存地址
                if (this.is_first == 0) {
                    var cache_address = uni.getStorageSync(app.globalData.data.cache_buy_user_address_select_key);
                    if ((cache_address || null) != null) {
                        this.setData({
                            address: cache_address,
                            address_id: cache_address.id
                        });
                    }
                }

                // 加载loding
                uni.showLoading({
                    title: '加载中...'
                });
                this.setData({
                    data_list_loding_status: 1
                });
                var data = this.params;
                data['customerId'] = this.user.role.id;
                data['createBy'] = this.user.username;
				console.log("data",data);
                uni.request({
                    url: app.globalData.get_request_url("buyIndex"),
                    method: 'POST',
                    data: data,
                    dataType: 'json',
					header:{
						'Tenant-Id':this.user.role.tenantId,
						'X-Access-Token':this.user.token,
					},
                    success: res => {
						console.log("init-buy(res)",res)
                        uni.stopPullDownRefresh();
                        uni.hideLoading();
                        if (res.data.code == 0) {
                            var data = res.data.data;
							console.log("init-buy(data)",data)
                            // 订单是否已提交、直接进入支付页面
                            if((data.is_order_submit || 0) == 1) {
                                this.buy_submit_response_handle(data);
                                return false;
                            }
                            // 处理订单初始化数据
                            if (data.goods_list.length == 0) {
                                this.setData({
                                    data_list_loding_status: 0
                                });
                            } else {
                                // 设置数据
                                this.setData({
                                    goods_list: data.goods_list,
                                    total_price: data.base.actual_price,
                                    extension_data: data.extension_data || [],
                                    data_list_loding_status: 3,
                                    common_site_type: data.common_site_type || 0,
                                    extraction_address: data.base.extraction_address || [],
                                    payment_list: data.payment_list || [],
                                    payment_id: data.default_payment_id || 0,
                                });



                                uni.setStorage({
                                    key: app.globalData.data.cache_buy_user_address_select_key,
                                    data: data.base.address || null
                                });
                            }
                        } else {
                            this.setData({
                                data_list_loding_status: 2,
                                data_list_loding_msg: res.data.msg
                            });
                            if (app.globalData.is_login_check(res.data, this, 'init')) {
                                app.globalData.showToast(res.data.msg);
                            }
                        }
                    },
                    fail: () => {
                        uni.stopPullDownRefresh();
                        uni.hideLoading();
                        this.setData({
                            data_list_loding_status: 2,
                            data_list_loding_msg: '服务器请求出错'
                        });
                        app.globalData.showToast('服务器请求出错');
                    }
                });
            },

            // 提交订单
            buy_submit_event(e) {
				if(this.customerId === ""){
					app.globalData.showToast('请选择客户!');
					return;
				}
                // 表单数据
				console.log("=====",this.user.userIdentity)
				if(this.user.userIdentity == 5){
					app.globalData.showToast('角色为[销售人员],无权限操作。');
					return;
				}
                var data = this.params;
				console.log("data",data)
                if (true) {
                    // 加载loding
                    uni.showLoading({
                        title: '提交中...'
                    });
                    this.setData({
                        buy_submit_disabled_status: true
                    });

					data['userIdentity'] =this.user.userIdentity,
					data['roleId'] = this.user.role.id,
					// console.log("user",this.user);
					// console.log("buy_submit_event(data)",data);
					data['customerId'] =this.customerId;
					data['billDate'] = this.billDate;
					data['salRemark'] =this.salRemark;

					data['remarks'] =this.inputs;

					console.log("remarks",data['remarks'])
					let remarksEx =[];
					for(var i = 0; i < data['ids'].split(',').length; i++){
						if(i >= data['remarks'].length){
							remarksEx[i] = '';
						}else{
							if(typeof data['remarks'][i] === 'undefined'){
								remarksEx[i] = '';
							}else{
								remarksEx[i] = data['remarks'][i];
							}
						}
					}
					data['remarks'] =remarksEx;
					console.log("data",data)

                    uni.request({
                        url: app.globalData.get_request_url("createBuyOrder"),
                        method: 'POST',
                        data: data,
						header:{
							'Tenant-Id':this.user.role.tenantId,
							'X-Access-Token':this.user.token,
						},
                        dataType: 'json',
                        success: res => {
                            uni.hideLoading();
							console.log("res",res)
                            if (res.data.code == 0) {
                                this.buy_submit_response_handle(res.data.data);
                            } else {
                                app.globalData.showToast(res.data.msg);
                                this.setData({
                                    buy_submit_disabled_status: false
                                });
                            }
                        },
                        fail: () => {
                            uni.hideLoading();
                            this.setData({
                                buy_submit_disabled_status: false
                            });
                            app.globalData.showToast('服务器请求出错');
                        }
                    });
                }
            },

            // 订单提交响应处理
            buy_submit_response_handle(data) {
                if (data.order_status == 1) {
                    var pay_data = {
                        order_ids: data.order_ids,
                        payment_id: data.payment_id
                    };
                    uni.setStorageSync(app.globalData.data.cache_page_pay_key, pay_data);
                }
                uni.redirectTo({
                    url: '/pages/user-order/user-order'
                });
            },

            // 仓库事件
            warehouse_group_event(e) {
                app.globalData.url_event(e);
            },
        }
    };
</script>
<style>
    @import './buy.css';
</style>
